package com.bj58.wuxian.lucene.highlighter;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.store.Directory;

import com.bj58.wuxian.lucene.constants.Constants;
import com.bj58.wuxian.lucene.utils.LuceneUtil;

public class HighlighterWrapper {

	public static void search(Directory directory, Analyzer analyzer, Query query, String fieldName) {

		
		DirectoryReader reader=null;
		try {
			Highlighter highlighter = LuceneUtil.getHighlighter(query, fieldName);
			reader = LuceneUtil.getDirectoryReader(directory);
			IndexSearcher isearcher = LuceneUtil.getIndexSearcher(reader);
			ScoreDoc[] hits = isearcher.search(query, 10).scoreDocs;

			for (int i = 0; i < hits.length; i++) {
				Document hitDoc = isearcher.doc(hits[i].doc);
				String reslut = highlighter.getBestFragment(analyzer, fieldName, hitDoc.get("context"));
				System.out.println(reslut);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					reader=null;
				}
			}
			if(directory!=null){
				try {
					directory.close();
				} catch (IOException e) {
					directory=null;
				}
			}
		}
	}

	public static void main(String[] args) throws ParseException {
		
		Directory directory = LuceneUtil.getDirectory(Constants.DIRECTROY_PATH);
		Analyzer analyzer = new StandardAnalyzer();
		QueryParser parser = new QueryParser("context", analyzer);
		Query query = parser.parse("apache");
		search(directory, analyzer, query, "context");
		
	}
}
